package org.suanfaTranning.ST200_Chatpter1_LineTable_HashTable_String.array;

import org.jikeshijian.Solution;

import java.util.HashSet;
import java.util.Set;

/**
 * @Auther: qingle
 * @Date: 2024/9/11-17:11
 * @Description:
 * @version: 1.0
 */
public class Solution_lengthOfLongestSubstring {
		public static int lengthOfLongestSubstring(String s) {
			// 用于存储字符是否出现过的集合
			Set<Character> set = new HashSet<>();
			int n = s.length();
			int maxLen = 0; // 最长不重复子串的长度
			int start = 0; // 滑动窗口的起始位置

			for (int end = 0; end < n; end++) {
				// 循环，直到窗口内没有重复字符
				while (set.contains(s.charAt(end))) {
					set.remove(s.charAt(start));
					start++;
				}
				// 将当前字符加入集合
				set.add(s.charAt(end));
				// 更新最长不重复子串的长度
				maxLen = Math.max(maxLen, end - start + 1);
			}

			return maxLen;
		}

		public static void main(String[] args) {
			Solution solution = new Solution();
			String input1 = "abcabcbb";
			System.out.println("Input: \"" + input1 + "\", Output: " + Solution_lengthOfLongestSubstring.lengthOfLongestSubstring(input1));

			String input2 = "bbbbb";
			System.out.println("Input: \"" + input2 + "\", Output: " + Solution_lengthOfLongestSubstring.lengthOfLongestSubstring(input2));

			String input3 = "pwwkew";
			System.out.println("Input: \"" + input3 + "\", Output: " + Solution_lengthOfLongestSubstring.lengthOfLongestSubstring(input3));
		}
	}